<template>
  <el-form 
    ref="formRef" 
    :model="form" 
    :rules="rules" 
    label-width="80px"
  >
    <!-- 姓名 -->
    <el-form-item label="姓名" prop="name">
      <el-input v-model="form.name" placeholder="请输入收货人姓名" />
    </el-form-item>
    
    <!-- 手机号 -->
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="form.phone" placeholder="请输入手机号码" />
    </el-form-item>
    
    <!-- 地区选择 -->
    <el-form-item label="所在地区" prop="region">
      <el-cascader 
        v-model="region" 
        :options="regionOptions" 
        placeholder="请选择所在地区"
        @change="handleRegionChange"
      />
    </el-form-item>
    
    <!-- 详细地址 -->
    <el-form-item label="详细地址" prop="detail">
      <el-input 
        v-model="form.detail" 
        type="textarea" 
        rows="2" 
        placeholder="街道、门牌号等详细信息"
      />
    </el-form-item>
    
    <!-- 默认地址 -->
    <el-form-item>
      <el-checkbox v-model="form.isDefault">设为默认收货地址</el-checkbox>
    </el-form-item>
    
    <!-- 表单按钮 -->
    <el-form-item>
      <el-button type="primary" @click="submitForm">保存</el-button>
      <el-button @click="cancelForm">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormValidateCallback } from 'element-plus';
import { Address } from '@/types/customer';
import { regionData } from './region-data'; // 引入省市区数据

const props = defineProps<{
  address?: Partial<Address>
}>();

const emit = defineEmits<{
  (e: 'submit', data: Partial<Address>): void
  (e: 'cancel'): void
}>();

// 表单引用
const formRef = ref<FormInstance>();

// 表单数据
const form = reactive<Partial<Address>>({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: false
});

// 区域选择数据
const region = ref<string[]>([]);
const regionOptions = ref(regionData);

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在5到100个字符之间', trigger: 'blur' }
  ]
};

// 监听地址属性变化，更新表单
watch(() => props.address, (newVal) => {
  if (newVal) {
    // 更新表单数据
    Object.assign(form, newVal);
    
    // 如果有省市区数据，更新级联选择器
    if (newVal.province && newVal.city && newVal.district) {
      region.value = [newVal.province, newVal.city, newVal.district];
    } else {
      region.value = [];
    }
  }
}, { immediate: true, deep: true });

// 处理地区变化
const handleRegionChange = (value: string[]) => {
  if (value.length === 3) {
    form.province = value[0];
    form.city = value[1];
    form.district = value[2];
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  try {
    const valid = await formRef.value.validate();
    // 确保地区数据已填写
    if (!form.province || !form.city || !form.district) {
      ElMessage.warning('请完整选择所在地区');
      return;
    }
    
    // 提交表单数据
    emit('submit', form);
  } catch (error) {
    ElMessage.warning('请完善表单信息');
  }
};

// 取消表单
const cancelForm = () => {
  emit('cancel');
};

// 组件初始化时，如果有传入地址，填充表单
onMounted(() => {
  if (props.address) {
    Object.assign(form, props.address);
    
    // 如果有省市区数据，更新级联选择器
    if (props.address.province && props.address.city && props.address.district) {
      region.value = [props.address.province, props.address.city, props.address.district];
    }
  }
});
</script>

<style scoped>
.el-form {
  max-width: 100%;
}

.el-cascader {
  width: 100%;
}
</style>
